package com.sgb.kjwl.view.ui.activity.self.pick;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import androidx.databinding.DataBindingUtil;
import android.os.Handler;
import android.os.Message;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.view.View;
import android.widget.EditText;

import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivitySearchListBinding;
import com.sgb.kjwl.di.self.DaggerSelfComponent;
import com.sgb.kjwl.di.self.SelfModule;
import com.sgb.kjwl.model.entity.InviteComEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.view.ui.adapter.self.InviteComAdapter;
import com.swgk.core.view.CityPickBuilder;
import com.swgk.core.view.CityPickView;
import com.sgb.kjwl.viewmodel.self.pick.InviteComModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.util.MLog;
import com.swgk.core.util.MToast;
import com.swgk.core.util.ResolutionUtil;
import com.swgk.core.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * author:zhao
 * 邀请公司bid投标,offer报价（选择需要邀请的企业）
 */
public class InviteComActivity extends AppActivity {
    private ActivitySearchListBinding binding;
    @Inject
    InviteComModel viewModel;
    private InviteComAdapter adapter;

    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;

    // 一级联动数据
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntityList;
    // 二级联动数据
    private List<List<AddressEntity<List<AddressEntity>>>> opt2;
    // 三级联动数据
    private List<List<List<AddressEntity>>> opt3;

    //区域列表
    private List<List<AddressEntity>> areaList;
    private int cityPosition1;
    private int cityPosition2;
    private int cityPosition3;
    private boolean isLoaded = false;
    private String district = "";
    private String type;
    private String no;

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerSelfComponent.builder().appComponent(appComponent).selfModule(new SelfModule(this)).build().inject(this);
    }

    /**
     * @param context
     * @param type    类型：邀请投标bid，邀请报价offer
     * @param no      项目编号
     */
    public static void start(Context context, String type, String no) {
        Intent intent = new Intent();
        intent.setClass(context, InviteComActivity.class);
        intent.putExtra("type", type);
        intent.putExtra("no", no);
        context.startActivity(intent);
    }

    @Override
    protected boolean statusBarDark() {
        return true;
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_search_list);
        binding.include.titleView.setText("搜索");
        binding.include.ivBack.setOnClickListener(this);
        binding.include.rightView.setOnClickListener(this);
        binding.checkAll.setOnClickListener(this);
        binding.tvInvite.setOnClickListener(this);
        binding.setViewModel(viewModel);
    }

    @Override
    protected void init() {
        type = getIntent().getStringExtra("type");
        no = getIntent().getStringExtra("no");
        opt2 = new ArrayList<>();
        opt3 = new ArrayList<>();
        getInviteList(false);
        adapter = new InviteComAdapter(this, null);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        binding.list.setLayoutManager(layoutManager);
        binding.list.setAdapter(adapter);
        binding.list.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                getInviteList(false);
            }

            @Override
            public void onLoadMore() {
                getInviteList(true);
            }
        });
        adapter.setOnCheckClick(new InviteComAdapter.onCheckListener() {
            @Override
            public void onCheck() {
                isAllChecked();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;

            case R.id.right_view:
                if (addressEntityList != null) {
                    showCityPop();
                } else {
                    viewModel.getAddressModel();
                }
                break;

            case R.id.check_all:
                ArrayList<InviteComEntity> inviteComEntities = new ArrayList<>();
                if (isAllChecked()) {
                    for (InviteComEntity entity : adapter.getDatas()) {
                        if (!entity.getButtonStatus().equals("1")) {
                            entity.setChoose(false);
                        }
                        inviteComEntities.add(entity);
                    }
                } else {
                    for (InviteComEntity entity : adapter.getDatas()) {
                        if (!entity.getButtonStatus().equals("1")) {
                            entity.setChoose(true);
                        }
                        inviteComEntities.add(entity);
                    }
                }

                adapter.setDatas(inviteComEntities);
                isAllChecked();
                break;

            case R.id.tv_invite:
                ArrayList<String> strings = new ArrayList<>();
                for (InviteComEntity entity : adapter.getDatas()) {
                    if (entity.isChoose()) {
                        strings.add(entity.getNo());
                    }
                }

                if (strings.size() == 0) {
                    MToast.showToast(InviteComActivity.this, "请选择需要邀请的企业");
                } else {
                    showInviteDialog(strings);
                }
                break;
        }
    }

    private void showInviteDialog(ArrayList<String> strings) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        final EditText et = new EditText(this);
        et.setLines(3);
        et.setHint("请输入报价规则");
        et.setPadding(ResolutionUtil.dp2px(this, 20), 0, ResolutionUtil.dp2px(this, 20), 0);
        et.setBackground(null);
        builder.setView(et);

        AlertDialog alertDialog = builder.setTitle("邀请确认：\n一共邀请了" + strings.size() + "家企业").setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                String substring = strings.toString().substring(1, strings.toString().length() - 1);
                MLog.i("params", substring + "  " + et.getText().toString());
                if (type.equals("offer")) {
                    viewModel.inviteOffer(substring, no, et.getText().toString());
                } else if (type.equals("bid")) {
                    viewModel.inviteBid(substring, no, et.getText().toString());
                }
            }
        }).setCancelable(true).create();
        alertDialog.show();
    }

    private void showCityPop() {
        CityPickView cityOption = new CityPickBuilder(InviteComActivity.this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                cityPosition1 = options1;
                cityPosition2 = options2;
                cityPosition3 = options3;
                district = opt3.get(options1).get(options2).get(options3).getNo();
                getInviteList(false);
            }
        }).build();
        cityOption.setPicker(addressEntityList, opt2, opt3);
        cityOption.setSelectOptions(cityPosition1, cityPosition2, cityPosition3);
        cityOption.show();
    }

    public void getInviteList(boolean b) {
        if ("bid".equals(type)) {
            viewModel.getInviteBidList(no, district, b);
        } else if ("offer".equals(type)) {
            viewModel.getInviteOfferList(no, district, b);
        }
    }

    public void showList(List<InviteComEntity> list, boolean isLoadMore) {
        if (isLoadMore) {
            binding.list.loadMoreComplete();
            if (list.size() != 0) {
                adapter.addDatas(list);
            }
        } else {
            if (list.size() == 0) {
                binding.emptyView.setVisibility(View.VISIBLE);
            } else {
                binding.emptyView.setVisibility(View.GONE);
            }

            binding.list.refreshComplete();
            binding.list.setLoadingMoreEnabled(true);
            adapter.setDatas(list);
        }
    }

    public void initAddressData(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
        this.addressEntityList = data;
        if (isLoaded) {
            showCityPop();
        } else {
            mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS:
                    showCityPop();
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    break;
            }
        }
    };

    private void initJsonData() {
        for (int i = 0; i < addressEntityList.size(); i++) {
            if (addressEntityList.get(i).getId().equals(viewModel.getAreaCode())) {
                cityPosition1 = i;
            }
            areaList = new ArrayList<>();
            opt2.add(addressEntityList.get(i).getChildren());
            for (int j = 0; j < addressEntityList.get(i).getChildren().size(); j++) {
                List<AddressEntity> cityAreaList = new ArrayList<>();
                List<AddressEntity> children = addressEntityList.get(i).getChildren().get(j).getChildren();
                if (children == null || children.size() == 0) {
                    cityAreaList.add(null);
                } else {
                    cityAreaList.addAll(children);
                }
                areaList.add(cityAreaList);
            }
            opt3.add(areaList);
        }
        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
    }

    /**
     * 判断当前是否为全选
     *
     * @return
     */
    private boolean isAllChecked() {
        boolean isAllChecked = true;
        for (InviteComEntity entity : adapter.getDatas()) {
            if (!entity.getButtonStatus().equals("1") && !entity.isChoose()) {
                isAllChecked = false;
            }
        }

        binding.checkAll.setChecked(isAllChecked);
        return isAllChecked;
    }
}
